/**
 * 
 */
package com.iwords.api.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.utils.CodeUtils;
import com.iwords.utils.Md5;


/**
 * @author       BOLIN.HBC 
 * @time         2011-4-8    
 * @description  安全验证的filter       
 */
//@WebFilter(filterName = "securityFilter", urlPatterns = { "/*" })
public class SecurityFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {

		if (process(req, res)) {
			filterChain.doFilter(req, res);
		} else {

			JSONObject result = new JSONObject();
			try {
				result.put("ERROR", CodeUtils.encode("恶意请求"));
			} catch (JSONException e) {

			}
		}
	}

	private boolean process(ServletRequest req, ServletResponse res) {
		HttpServletRequest request = (HttpServletRequest) req;
		String url = request.getRequestURL().append("?").append(request.getQueryString()).toString();
		String token = req.getParameter("k");
		if (token == null || token.length() == 0) {
			return false;
		}
		String k = Md5.compute(url.substring(0, url.indexOf("&k="))).substring(0, 16);
		if (token.equals(k)) {
			return true;
		}

		return false;

	}

	public void init(FilterConfig arg0) throws ServletException {

	}

}
